package cn.fntop.controller;

import cn.fntop.constant.TenantConstants;
import cn.fntop.entity.User;
import cn.fntop.service.UserService;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author fn
 * @description
 * @date 2024/1/25 15:31
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/muti/tenant/")
@Slf4j
public class UserController {
    private final UserService userService;

    @GetMapping("/save")
    public String save(HttpServletRequest request) {
        String tenantId = request.getHeader(TenantConstants.TENANT_ID) == null ? "1" : request.getHeader(TenantConstants.TENANT_ID);
        userService.save(User.builder()
                .username("username" + tenantId + "_" + RandomUtil.randomNumbers(5))
                .mobile("mobile1" + tenantId + "_" + RandomUtil.randomNumbers(11))
                .build()
        );
        return "保存数据到【test" + tenantId + "】表中";
    }

    @GetMapping("/deleteById")
    public String deleteById(HttpServletRequest request, Long id) {
        String tenantId = request.getHeader(TenantConstants.TENANT_ID) == null ? "1" : request.getHeader(TenantConstants.TENANT_ID);
        userService.removeById(User.builder().id(id).build());
        return "逻辑删除【test" + tenantId + "】表中的数据";

    }
    @GetMapping("/update")
    public String update(HttpServletRequest request, Long id) {
        String tenantId = request.getHeader(TenantConstants.TENANT_ID) == null ? "1" : request.getHeader(TenantConstants.TENANT_ID);
        userService.updateById(userService.getById(id));
        return "更新【test" + tenantId + "】表中的数据";

    }
    @GetMapping("/page")
    public Page page(HttpServletRequest request, Page page) {
        String tenantId = request.getHeader(TenantConstants.TENANT_ID) == null ? "1" : request.getHeader(TenantConstants.TENANT_ID);
        log.info("分页查询【test{}】表中的数据", tenantId);
        Page result = userService.page(page);
        return result;
    }

}
